import Footer from '@/components/Footer';
import {login, register} from '@/services/ant-design-pro/api';
import {LockOutlined, UserOutlined,} from '@ant-design/icons';
import {LoginForm, ProFormText,} from '@ant-design/pro-components';
import {Alert, message, Tabs} from 'antd';
import React, {useState} from 'react';
import {history, useModel} from 'umi';
import styles from './index.less';
import {useForm} from "antd/es/form/Form";

const LoginMessage: React.FC<{
    content: string;
}> = ({content}) => (
    <Alert
        style={{
            marginBottom: 24,
        }}
        message={content}
        type="error"
        showIcon
    />
);
const Login: React.FC = () => {
    const [userLoginState, setUserLoginState] = useState<API.ResponseResult>({errCode: "", errMessage: "", success: false});
    const [userRegisterState, setUserRegisterState] = useState<API.ResponseResult>({errCode: "", errMessage: "", success: false});
    const [type, setType] = useState<string>('login');
    const {initialState, setInitialState} = useModel('@@initialState');
    const fetchUserInfo = async () => {
        const userInfo = await initialState?.fetchUserInfo?.();
        if (userInfo) {
            await setInitialState((s) => ({
                ...s,
                currentUser: userInfo,
            }));
        }
    };
    const [form] = useForm();
    const handleSubmit = async (values: API.RegisterParams) => {
        const fnc = type === 'login' ? login : register;
        const msg = await fnc({
            ...values
        });
        if (!msg.success) {
            // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            type === 'login' ? setUserLoginState(msg) : setUserRegisterState(msg);
            return;
        }
        const defaultLoginSuccessMessage = type === 'login' ? '登录成功' : '注册成功';
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        if (type === 'login') {
            if (!history) return;
            const {query} = history.location;
            const {redirect} = query as {
                redirect: string;
            };
            history.push(redirect || '/');
        } else {
            setType('login');
            form.resetFields();
        }
    };
    const handleChange = (key: string) => {
        setType(key);
        form.resetFields();
        setUserLoginState({errCode: "", errMessage: "", success: false});
        setUserRegisterState({errCode: "", errMessage: "", success: false});
    };
    const {errCode, errMessage} = type === 'login' ? userLoginState : userRegisterState;
    return (
        <div className={styles.container}>
            <div className={styles.content}>
                <LoginForm
                    form={form}
                    submitter={{
                        searchConfig: {
                            submitText: type === 'login' ? '登录' : '注册',
                        }
                    }}
                    logo={<img alt="logo" src="/logo.svg"/>}
                    title="UserHub"
                    subTitle={'UserHub 用户统一集中接入平台'}
                    onFinish={async (values) => {
                        await handleSubmit(values as API.RegisterParams);
                    }}
                >
                    <Tabs activeKey={type} onChange={handleChange}>
                        <Tabs.TabPane key="login" tab={'账户密码登录'}/>
                        <Tabs.TabPane key="register" tab={'新用户注册'}/>
                    </Tabs>

                    {errCode && type === 'login' && (
                        <LoginMessage content={errMessage || '登录失败'}/>
                    )}
                    {type === 'login' && (
                        <>
                            <ProFormText
                                name='userAccount'
                                fieldProps={{
                                    size: 'large',
                                    prefix: <UserOutlined className={styles.prefixIcon}/>,
                                }}
                                placeholder={'请输入账号'}
                                rules={[
                                    {
                                        required: true,
                                        message: '账号是必填项',
                                    },
                                    {
                                        pattern: /^[a-zA-Z0-9]{6,}$/,
                                        message: '账号不能包含特殊字符且长度不少于6',
                                    }
                                ]}
                            />
                            <ProFormText.Password
                                name="userPassword"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined className={styles.prefixIcon}/>,
                                }}
                                placeholder={'请输入密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: '密码是必填项',
                                    },
                                    {
                                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/,
                                        message: '密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间',
                                    }
                                ]}
                            />
                        </>
                    )}

                    {errCode && type === 'register' && (
                        <LoginMessage content={errMessage || '注册失败'}/>
                    )}
                    {type === 'register' && (
                        <>
                            <ProFormText
                                fieldProps={{
                                    size: 'large',
                                    prefix: <UserOutlined className={styles.prefixIcon}/>,
                                }}
                                name="userAccount"
                                placeholder={'请输入账号'}
                                rules={[
                                    {
                                        required: true,
                                        message: '账号是必填项',
                                    },
                                    {
                                        pattern: /^[a-zA-Z0-9]{6,}$/,
                                        message: '账号不能包含特殊字符且长度不少于6',
                                    }
                                ]}
                            />
                            <ProFormText.Password
                                name="userPassword"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined className={styles.prefixIcon}/>,
                                }}
                                placeholder={'请输入密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: '密码是必填项',
                                    },
                                    {
                                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/,
                                        message: '密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间',
                                    }
                                ]}
                            />
                            <ProFormText.Password
                                name="checkPassword"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined className={styles.prefixIcon}/>,
                                }}
                                placeholder={'请再次输入密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: '密码是必填项',
                                    },
                                    {
                                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/,
                                        message: '密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间',
                                    }
                                ]}
                            />
                        </>
                    )}
                </LoginForm>
            </div>
            <Footer/>
        </div>
    );
};
export default Login;